const chapter = document.querySelector('.chapter')
const ico = document.querySelector('.ico')
const icoon = document.querySelector('.icoon')

//渲染目录
const a=()=> {
    fetch('https://www.iceread.com/api/story/chapters?volumeId=10021775&cb=1756284829280').then(res=> res.json()).then(res1=> {
        res1.chapters.forEach((item,index)=> {
            chapter.innerHTML+=`
                <a href="">${item.name}
                ${item.isPay==1?`<img src="https://c.hotread.com/girlPc/assets/images/pay.png" alt="">`:''} </a>
                
            `
        })
    }).catch(err=> {
        console.log(err);
    })
}
a()

//点击实现目录的展开
let chapterbol = true
const expand = () => {
    console.log(1111);
    if(chapterbol){
        chapter.style.display = 'none'
        chapterbol =!chapterbol
        ico.style.display = 'none'
        icoon.style.display = 'block'
    }else {
        chapter.style.display = 'block'
        chapterbol =!chapterbol
        ico.style.display = 'block'
        icoon.style.display = 'none'
    }
}
const searchState = {
    novelData: [], // 存储接口返回的所有小说数据
    filteredData: [], // 筛选后的数据
    debounceTimer: null, // 防抖定时器
    currentKeyword: '', // 当前搜索关键词
    isLoading: false // 加载状态标识
};

// DOM 元素缓存（基于原始 HTML 结构）
const domElements = {
    searchInput: document.getElementById('searchInput'),
    searchBtn: document.getElementById('searchBtn'),
    // 动态创建结果容器（不修改原始 HTML，追加到搜索框下方）
    resultContainer: (() => {
        const container = document.createElement('div');
        container.id = 'searchResultContainer';
        container.style.cssText = `
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            margin-top: 8px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            z-index: 100;
            max-height: 400px;
            overflow-y: auto;
            display: none;
        `;
        // 将结果容器插入到搜索框父元素中
        document.querySelector('.search-content').appendChild(container);
        return container;
    })()
};

// 初始化：加载小说数据并绑定事件
async function initSearch() {
    // 优先加载接口数据
    await fetchNovelData();
    // 绑定交互事件
    bindSearchEvents();
}

// 调用小说接口获取数据
async function fetchNovelData() {
    try {
        const response = await fetch('https://www.iceread.com/api/common/rank/6273/0/1291');
        if (!response.ok) throw new Error('接口请求失败');
        
        const data = await response.json();
        // 提取小说核心数据（适配接口返回格式）
        searchState.novelData = data.list ? data.list.map(item => item.story || item) : [];
        searchState.filteredData = [...searchState.novelData];
    } catch (error) {
        console.error('小说数据加载失败:', error);
        renderResult(`<div style="padding:16px;text-align:center;color:#999;">数据加载失败，请稍后重试</div>`);
    }
}

// 绑定搜索相关事件
function bindSearchEvents() {
    // 搜索按钮点击
    domElements.searchBtn.addEventListener('click', handleSearch);
    
    // 输入框实时输入（防抖处理）
    domElements.searchInput.addEventListener('input', () => {
        searchState.currentKeyword = domElements.searchInput.value.trim().toLowerCase();
        
        // 清空关键词时隐藏结果容器
        if (!searchState.currentKeyword) {
            domElements.resultContainer.style.display = 'none';
            return;
        }
        
        // 防抖：300ms 内连续输入不触发搜索
        clearTimeout(searchState.debounceTimer);
        searchState.debounceTimer = setTimeout(handleSearch, 300);
    });
    
    // 回车键触发搜索
    domElements.searchInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') handleSearch();
    });
    
    // 点击页面其他区域隐藏结果容器
    document.addEventListener('click', (e) => {
        const isClickInside = domElements.searchInput.contains(e.target) || 
                             domElements.searchBtn.contains(e.target) || 
                             domElements.resultContainer.contains(e.target);
        if (!isClickInside) {
            domElements.resultContainer.style.display = 'none';
        }
    });
}

// 核心搜索逻辑
function handleSearch() {
    const keyword = searchState.currentKeyword;
    
    // 显示加载状态
    showLoading();
    
    // 筛选逻辑：匹配小说名、作者、标签
    searchState.filteredData = searchState.novelData.filter(novel => {
        const matchName = novel.name?.toLowerCase().includes(keyword) || false;
        const matchAuthor = novel.author?.toLowerCase().includes(keyword) || false;
        const matchTag = novel.tag?.toLowerCase().includes(keyword) || false;
        return matchName || matchAuthor || matchTag;
    });
    
    // 渲染搜索结果
    renderResult();
}

// 渲染搜索结果
function renderResult(customContent = '') {
    // 隐藏加载状态
    hideLoading();
    
    // 显示结果容器
    domElements.resultContainer.style.display = 'block';
    
    // 自定义内容渲染（如错误提示）
    if (customContent) {
        domElements.resultContainer.innerHTML = customContent;
        return;
    }
    
    // 无结果处理
    if (searchState.filteredData.length === 0) {
        domElements.resultContainer.innerHTML = `
            <div style="padding:24px;text-align:center;">
                <div style="font-size:24px;color:#ccc;margin-bottom:8px;">&#128270;</div>
                <p style="color:#666;">未找到包含「${searchState.currentKeyword}」的小说</p>
                <p style="color:#999;font-size:12px;margin-top:4px;">建议尝试其他关键词</p>
            </div>
        `;
        return;
    }
    
    // 渲染小说列表
    let resultHtml = '';
    searchState.filteredData.forEach(novel => {
        // 关键词高亮处理
        const highlight = (text) => {
            if (!text || !searchState.currentKeyword) return text;
            const regex = new RegExp(`(${searchState.currentKeyword})`, 'gi');
            return text.replace(regex, '<span style="color:#6366f1;font-weight:500;">$1</span>');
        };
        
        // 小说标签处理
        const tags = novel.tag ? novel.tag.split(',').slice(0, 2) : [];
        const tagHtml = tags.map(tag => `
            <span style="font-size:12px;padding:2px 6px;background:#f3f4f6;color:#666;border-radius:4px;margin-right:4px;">${highlight(tag)}</span>
        `).join('');
        
        // 单个小说项 HTML
        resultHtml += `
            <div style="padding:12px;border-bottom:1px solid #f5f5f5;cursor:pointer;" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background='transparent'" onclick='jumps(${JSON.stringify(novel)})'>
                <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:4px;">
                    <h4 style="margin:0;font-size:14px;color:#333;">${highlight(novel.name)}</h4>
                    ${novel.isPay === 1 ? '<span style="font-size:12px;color:#ef4444;background:#fee2e2;padding:1px 4px;border-radius:3px;">VIP</span>' : ''}
                </div>
                <p style="margin:0 0 6px 0;font-size:12px;color:#999;">作者：${highlight(novel.author)}</p>
                <div style="margin-bottom:6px;">${tagHtml}</div>
                <p style="margin:0;font-size:12px;color:#666;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                    ${highlight(novel.introduce ? novel.introduce.slice(0, 100) + '...' : '暂无简介')}
                </p>
            </div>
        `;
    });
    
    domElements.resultContainer.innerHTML = resultHtml;
}
function jumps(hearf){
       location.href=`./channelDetail.html?${JSON.stringify(hearf)}`
    }
// 显示加载状态
function showLoading() {
    searchState.isLoading = true;
    domElements.resultContainer.style.display = 'block';
    domElements.resultContainer.innerHTML = `
        <div style="padding:24px;text-align:center;">
            <div style="width:20px;height:20px;border:2px solid #6366f1;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 8px;"></div>
            <p style="color:#666;font-size:12px;">正在搜索...</p>
        </div>
    `;
    // 添加加载动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
}

// 隐藏加载状态
function hideLoading() {
    searchState.isLoading = false;
}

// 页面加载完成后初始化搜索功能
document.addEventListener('DOMContentLoaded', initSearch);
